package com.linwen.excise.leetcode;


/**
 * @author : linwen
 * @date : 下午10:16 2021/2/14
 */
public class _2两数相加 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l1n1 = new ListNode(4);
        l1.next = l1n1;
        ListNode l1n2 = new ListNode(3);
        l1n1.next = l1n2;

        ListNode l2 = new ListNode(5);
        ListNode l2n1 = new ListNode(6);
        l2.next = l2n1;
        ListNode l2n2 = new ListNode(4);
        l2n1.next = l2n2;

        ListNode result = new _2两数相加().addTwoNumbers(l1,l2);
        while (result!=null){
            System.out.print(result.val+"  ");
            result = result.next;
        }

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode root = result;//根结点
        int carry = 0;
        while(l1!=null || l2!=null || carry!=0){
            int var1 = l1!=null?l1.val:0;
            int var2 = l2!=null?l2.val:0;
            int sum = var1+var2+carry;
            carry = sum/10;
            ListNode temp = new ListNode(sum%10);
            result.next = temp;
            result = temp;

            if(l1!=null){l1 = l1.next;}
            if(l2!=null){l2 = l2.next;}
        }
        return root.next;//头节点初始值默认为0，正式值是next
    }
}

